(function() {
  var _id;
  var _players;

  var _soket;

  var _upCard;
  var _cards;
  var _dealer;
  var _whichTurn;
  var _phase;
  var _gamer;
  var _kozir;

  deberc.gameRoom = {
    getKozir: function() {
      return _kozir;
    },
    getPhase: function() {
      return _phase;
    },
    getWhichTurn: function() {
      return _whichTurn;
    },
    getCards: function() {
      return _cards;
    },
    getUpCard: function() {
      return _upCard;
    },
    getDealer: function() {
      return _dealer;
    },
    getId: function() {
      return _id;
    },
    isMyIndex: function(index) {
      return deberc.rest.session.isCurrent(_players[index]);
    },
    setPlayers: function(players) {
      _players = players;
    },
    getPlayers: function() {
      return _players;
    },
    move: function(params) {
      deberc.rest.manager.move(_id, params, this, function(response) {
        console.debug(response);
      });
    },
    leave:function() {
      deberc.rest.manager.move(_id, 'l', this, function(response) {
        console.debug(response);
      });
      _soket.close();
      deberc.gameStarter.hide();
      deberc.gameRoomView.hide();
      deberc.mainRoom.enter();
    },
    enter:function(id) {
      _id = id;
      deberc.rest.manager.enterRoom(id, this, this._onGetToken);
    },
    _onGetToken: function(token) {
      var channel = new goog.appengine.Channel(token);
      var that = this;
      _soket = channel.open({
          onopen: function() {
          },
          onmessage: function(m) {
            that.onChange(m);
          },
          onerror: function() {
          },
          onclose: function() {
          }
        });
      deberc.rest.manager.move(_id, 'j', this, function(response) {
        if (response.code == 2) {
          alert(response.message);
          _soket.close();
          deberc.gameStarter.hide();
          deberc.gameRoomView.hide();
          deberc.mainRoom.enter();
        }
        else if (response.code == 1) {
          alert(response.message);
        }
      });
    },
    onChange: function(response) {
      response.data = response.data.match(/(^\S*)/g)[0];
      var data = response.data.split(';');
      if (data[0] === '100') {
        alert(data[2]);
        if (data[1] == '0') {
          this.leave();
        }
      }
      else if (data[0] === '0') {
        deberc.gameStarter.render(data);
      }
      else if (data[0] === '52') {
        alert('Извините, эта игра завершается, потому что один из игроков покинул её.')
        _soket.close();
        deberc.gameStarter.hide();
        deberc.gameRoomView.hide();
        deberc.mainRoom.enter();
      }
      else if (data[0] === '1') {
        _phase = data[0];
        _cards = data[3].split(',');
        _upCard = data[2];
        _dealer = parseInt(data[1]);
        _whichTurn = (_dealer + 1) % _players.length;

        deberc.gameStarter.hide();
        deberc.gameRoomView.render();
      }
      else if (data[0] === 'p') {
        if (_whichTurn == _dealer) {
          _phase = '2';
        }
        _whichTurn = (_whichTurn + 1) % _players.length;

        deberc.gameStarter.hide();
        deberc.gameRoomView.render();
      }
      else if (data[0] === 'w') {
        _whichTurn = (_whichTurn + 1) % _players.length;

        deberc.gameStarter.hide();
        deberc.gameRoomView.render();
      }
      else if (data[0] === 'k') {
        _gamer = _whichTurn;
        _kozir = _upCard.substr(1);
        _phase = '3';
        var newCards = data[1].split(',');
        for (var i in newCards) {
          _cards.push(newCards[i]);
        }

        deberc.gameStarter.hide();
        deberc.gameRoomView.render();
      }
      else if (data[0] === 't') {
        _gamer = _whichTurn;
        _kozir = data[2];
        _phase = '3';
        var newCards = data[1].split(',');
        for (var i in newCards) {
          _cards.push(newCards[i]);
        }

        deberc.gameStarter.hide();
        deberc.gameRoomView.render();
      }
      else if (data[0] === 'm') { //mel move processing
        var card1 = data[1];
        for (var i in _cards) {
          if (_cards[i] == card1) {
            _cards[i] = null;
          }
        }

        // TODO: stub to show to players which cxard were moved
        document.getElementById('monitor').innerHTML += '; ' + data[1];

        var whoGoes = data[2];//c - player changing ; n - player the same; f - ending of deal
        if (whoGoes == 'c') {
          _whichTurn = (_whichTurn + 1) % _players.length;
        }
        var index = _whichTurn;
        var roundPoints = parseInt(data[3]);
        var result = parseInt(document.getElementById('td' + index).innerHTML);
        result += roundPoints;
        document.getElementById('td' + index).innerHTML = result;
        deberc.gameStarter.hide();
        deberc.gameRoomView.render();
        if (whoGoes === 'f') {//finish sda4a
          var well = data[4];
          if (well === 'n') {//if 'gamer' didn't get enough points to win this deal, his points come to opponent
            var gamerPts = parseInt(document.getElementById('td' + _gamer).innerHTML);
            var opponentIndex = (_gamer + 1) % _players.length;
            var opponentPts = parseInt(document.getElementById('td' + opponentIndex).innerHTML);
            opponentPts += gamerPts;
            document.getElementById('td' + opponentIndex).innerHTML = opponentPts;
            document.getElementById('td' + _gamer).innerHTML = 0;
          }
          document.getElementById('tbl').
            innerHTML += '<tr>' + document.getElementById('tbl_cntnt').innerHTML + '</tr>';//copying info for full statistic table
          var nextNum = parseInt(document.getElementById('td2').innerHTML);//deal number
          nextNum++;
          document.getElementById('td2').innerHTML = nextNum;
          document.getElementById('td0').innerHTML = '0';
          document.getElementById('td1').innerHTML = '0';
          document.getElementById('monitor').innerHTML = '';
          deberc.gameRoom.move('s');
          alert("finish");
          deberc.gameStarter.hide();
          deberc.gameRoomView.render();
        }
      }
    }
  };
})();
